import $ from '../jquery/jquery.min.js';
import ajax from '../utils/ajax'

const searchObj = {
    value: '',
    currentPage: 1,
    pageSize: 5,
    pages: 0,
    total: 0
}


//加载页面上的客户信息
showCustomerData();
showPageData();

// 点击新增打开模态框
$('#customerManagement').on('click', '.show-customer-modal', function () {
    $("#add-customer-modalbox").show();
    if ($(this).text()=='编辑') {
        $("#customer-title-h4").text('修改资料');
        //获取选择要修改用户的数据渲染到模态框
        const _id = $(this).data('id');
        $('#customer-title-h4').attr('data-id', _id);
        getCustomerById(_id);
    } else {

    }
});


//点击关闭模态框
$('#add-customer-modalbox').on('click', '.cancle-customer-btn', function () {
    clearData();
    $("#add-customer-modalbox").hide();
    $("#customer-title-h4").text('新增客户');
});


//新增客户 / 修改客户资料
$('#ok-btn').click(function () {
    //获取页面上输入的信息
    const _id = $('#customer-title-h4').data('id');
    const name = $("#customerName").val();
    const gender = $('[name=sex]:checked').val();
    const tel = $('#customerTel').val();
    const type = $('#customerSelect').val();
    const purpose = $('#leaseSelect').val();
    const administrator = $('#pjw666').text();
    const date = getDate();
    const remark = $('#customerremark').val();
    if(name!=''&&tel!=''){
        if ($("#customer-title-h4").text() == '新增客户') {
            //发送新增请求
            ajax({
                url: '/customer',
                type: 'POST',
                data: {
                    name,
                    gender,
                    tel,
                    type,
                    purpose,
                    administrator,
                    date,
                    remark
                },
                success(res) {
                    if (res.code == 200) {
                        alert('添加成功');
                        //关闭模态框
                        clearData();
                        $("#add-customer-modalbox").hide();
                        if ($('#customer-tb tbody tr').length == searchObj.pageSize) {
                            showPageData();
                        }
                        showCustomerData();
                    } else {
                        alert('添加失败');
                        //关闭模态框
                        clearData();
                        $("#add-customer-modalbox").hide();
                        showCustomerData();
                    }
                }
            });
        } else {
            //修改用户资料
            ajax({
                url: '/customer',
                data: {
                    _id,
                    name,
                    gender,
                    tel,
                    type,
                    purpose,
                    administrator,
                    date,
                    remark
                },
                type: "PUT",
                success(res) {
                    if (res.code == 200) {
                        //关闭模态框
                        clearData();
                        $("#add-customer-modalbox").hide();
                        showCustomerData();
                        $("#customer-title-h4").text('新增客户');
                    } else {
                        alert('修改客户资料失败');
                        clearData();
                        $("#add-customer-modalbox").hide();
                    }
                }
            });
        } 
    }else{
        alert('客户姓名和电话都不能为空!');
    }
 



});


//获取当前日期
function getDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = parseInt(date.getMonth()) + 1;
    const day = date.getDate();
    return `${year}-0${month}-${day}`;
}

//关闭模态框后清除所有表单数据
function clearData() {
    $("#customerName").val('');
    $('#customerTel').val('');
    $('#customerremark').val('');
    $(`input[value=男]`).prop('checked', true);
}

//渲染顾客数据
function showCustomerData() {
    ajax({
        url: "/customer",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                searchObj.pages = res.pages;
                searchObj.total = res.total;
                renderCustomer(res.result);
            } 
        }
    })
}

function renderCustomer(data) {
    $('#customer-tb tbody').html(data.map(item => `<tr>
    <td>${item.name}</td>
    <td>${item.gender}</td>
    <td>${item.tel}</td>
    <td>${item.type}</td>
    <td>${item.purpose}</td>
    <td>${item.administrator}</td>
    <td>${item.date}</td>
    <td>
    <a class='show-customer-modal' data-id=${item._id}>编辑</a>
    <span class='del-customer-btn' data-id=${item._id}>删除</span>
    </td>
</tr>`).join(''));
}


//渲染下面的页面大小相关内容

function showPageData() {
    ajax({
        url: "/customer",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                renderPageData(Number(res.pages));
            }
        }
    })
}

function renderPageData(pages) {
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<span>${i}</span>`;
    }
    $('#customer-bottom-choose-page-div .add-pages-span').html(html);
    $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
}




//点击删除按钮，删除对应客户数据
$('#customer-tb tbody').on('click', '.del-customer-btn', function () {
    const _id = $(this).data('id');
    delCustomer(_id);
});






//删除客户数据
function delCustomer(_id) {
    ajax({
        url: '/customer',
        data: { _id },
        type: "DELETE",
        success(res) {
            if (res.code == 200) {
                //删除成功
                if ((searchObj.total) % (searchObj.pageSize) == 1) {
                    $('#customer-tb tbody tr').length == 1 ? searchObj.currentPage-- : searchObj.currentPage;
                    showPageData();
                }
                showCustomerData();
            } else {
                alert('抱歉,删除失败');
            }
        }
    })
}


//点击切换页面
$('#customer-bottom-choose-page-div .add-pages-span').on('click', 'span', function () {
    $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(this).addClass('active');
    const currentPage = $(this).text();
    searchObj.currentPage = Number(currentPage);
    showCustomerData();
});

//点击切换页面显示条数
$('#customer-pageSize-select').change(function () {
    const pageSize = $('#customer-pageSize-select').val();
    searchObj.pageSize = Number(pageSize);
    searchObj.currentPage = 1;
    showCustomerData();
    showPageData();
});


//跳至X页事件
$('#customer-go-page').keyup(function (e) {
    if (e.keyCode == 13) {
        const page = $('#customer-go-page').val();
        if (page != '' && typeof Number(page) == 'number' && !isNaN(Number(page))) {
            if (Number(page) < 1) {
                searchObj.currentPage = 1;
                showCustomerData();
                $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else if (Number(page) > searchObj.pages) {
                searchObj.currentPage = searchObj.pages;
                showCustomerData();
                $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else {
                searchObj.currentPage = Number(page);
                showCustomerData();
                $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            }
        }
    }
});


//上一页，下一页事件
$('#customer-prev-span').click(function () {
    if (searchObj.currentPage <= 1) {
        searchObj.currentPage = 1;
    } else {
        searchObj.currentPage--;
    }
    showCustomerData();
    $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});

$('#customer-next-span').click(function () {
    if (searchObj.currentPage == searchObj.pages) {
        searchObj.currentPage = searchObj.pages;
    } else {
        searchObj.currentPage++;
    }
    showCustomerData();
    $('#customer-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#customer-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});




//点击搜索按钮查询
$('#search-btn').click(function () {
    const value = $('#customer-search').val();
    searchObj.value = value;
    searchObj.currentPage = 1;
    showCustomerData();
    showPageData();
});





//通过id查询对应的客户资料
function getCustomerById(_id) {
    ajax({
        url: '/customer/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                const { name, gender, tel, type, purpose, remark } = res.result;
                $("#customerName").val(name);
                $(`input[value=${gender}]`).prop('checked', true);
                $('#customerTel').val(tel);
                $('#customerSelect').val(type);
                $('#leaseSelect').val(purpose);
                $('#customerremark').val(remark);
            } 
        }
    })
}